<?php
/**
 * @package Application_Controller
 * @author Cezar Zaleski e Reginaldo Júnior
 * @version 1.0.88
 */

/**
 * @namespace
 */
namespace Application\Controller;
/**
 * @uses Zend\Mvc\Controller\AbstractActionController
 * @uses Zend\View\Model\ViewModel
 * @uses Zend\Authentication\AuthenticationService
 * @uses Zend\Authentication\Storage\Session
 * @uses Application\Form\AuthForm
 * @uses Application\Repository\UsuarioRepository
 * @uses Doctrine\ORM\EntityManager
 * @uses Application\Service\UsuarioService
 * @uses Application\Auth\UsuarioAuth
 */
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Storage\Session as SessionStorage;
use Application\Form\AuthForm;
use Application\Repository\UsuarioRepository;
use Doctrine\ORM\EntityManager;
use Application\Service\UsuarioService;
use Application\Auth\UsuarioAuth;
use Zend\Http\Header\SetCookie;
use Zend\Crypt\Key\Derivation\Scrypt;
use Zend\Math\Rand;
use Doctrine\DBAL\Schema\View;
use Zend\Config\Reader\Json;

/**
 * Objeto de controle de autenticação de usuário
 */
class IndexController extends AbstractActionController
{
	
	/**
	 * @var EntityManager
	 */
	protected $em;
	
	protected $error;
	/**
	 * Método para logar o usuário
	 *
	 * @access public
	 * @return Zend\View\Model\ViewModel
	 */
	public function indexAction()
	{
		if(isset($this->getRequest()->getHeaders()->get('Cookie')->usuario)){
			$user = $this->verifyCookie($this->getRequest()->getHeaders()->get('Cookie')->usuario);
			if($user){
				return $this->logar($user->getNoUsuario(), $user->getNoSenha(), NULL);
			}
			return $this->redirect()->toRoute('home');
		}else{
			$form = new AuthForm();
			$error = false;
			$request = $this->getRequest();
			if($request->isPost()){
				$form->setData($request->getPost());
				if ($form->isValid()) {
					$data = $request->getPost();
					$this->logar($data->offsetGet('noLogin'), sha1($data->offsetGet('noSenha')), $form->get('stLembreme')->getValue());
				}else{
					$this->$error = true;
				}
			}
			$vielModel = new ViewModel(array('form' => $form, 'error' => $this->error));
			return $vielModel;
		}
		$vielModel = new ViewModel();
		return $vielModel->setTerminal(true);
	}
	/**
	 * Metodo para logout
	 *
	 * @access public
	 * @return Redirect home
	 */
	public function logoutAction()
	{
		$auth = new AuthenticationService;
		$auth->setStorage(new SessionStorage('Geccal'));
		$auth->clearIdentity();
		$cookie = new SetCookie('usuario', '', -86400);
		$response = $this->getResponse()->getHeaders();
		$response->addHeader($cookie);
		return $this->redirect()->toRoute('home');
	}
	/**
	 * Metodo carregar menu
	 *
	 * @access public
	 * @return Json
	 */
	public function loadingMenuAction()
	{
		$request = $this->getRequest();
		if($request->isPost())
		{
		    $this->em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
		    $repository = $this->em->getRepository("Application\Entity\Funcionalidade");
		    $data = $repository->findByFuncPerfilMod(1,1);
		    $menuLateral;
// 		    foreach ($data as $val)
// 		    {
// 		        $menuLateral = "<li>
//                      		    <a href='#'>
//                     		    <i class='fa fa-bar-chart-o fa-fw'></i>
//                     		    {$val['noMenuSubmodulo']}
//                     		    <span class='fa arrow'></span>
//                     		    </a>
//                     		    <ul class='nav nav-second-level'>
//                     		    <li>
//                     		    <a href='flot.html'>{$val['noMenuFuncionalidade']}</a>
//                     		    </li>
//                     		    </ul>
//                     		    <!-- /.nav-second-level -->
//                     		    </li>";
// 		    }    
// 		    <li>
// 		    <a href="#">
// 		    <i class="fa fa-bar-chart-o fa-fw"></i>
// 		    Charts
// 		    <span class="fa arrow"></span>
// 		    </a>
// 		    <ul class="nav nav-second-level">
// 		    <li>
// 		    <a href="flot.html">Flot Charts</a>
// 		    </li>
// 		    <li>
// 		    <a href="morris.html">Morris.js Charts</a>
// 		    </li>
// 		    </ul>
// 		    <!-- /.nav-second-level -->
// 		    </li>
		    
		}else
		{
			
		}
		
    $response = $this->getResponse();
    $response->setStatusCode(200);
    $response->setContent(json_encode($data));

    $headers = $response->getHeaders();
    $headers->addHeaderLine('Content-Type', 'application/json');

    return $response;
	}
	/**
	 * Metodo para setar cookie
	 *
	 * @access protected
	 * @param \stdClass $usuario
	 */
	protected function setCookie($usuario)
	{
		$rand = Rand::getBytes(strlen($usuario->idUsuario), true);
		$key  = bin2hex(Scrypt::calc($usuario->idUsuario, $rand, 2048, 2, 1, 64));
		$service = $this->getServiceLocator()->get("Application\Service\UsuarioService");
		$service->update($usuario->idUsuario,array('stCookie'=>$key));
		 
		$cookie = new SetCookie('usuario', $key, time() + 7 * 60 * 60 * 24);
		$response = $this->getResponse()->getHeaders();
		$response->addHeader($cookie);
	}
	
	protected function verifyCookie($cookie)
	{
		$this->em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
		$repository = $this->em->getRepository("Application\Entity\Usuario");
		return $repository->findByCookie($cookie); 
	}
	
	protected function logar($noLogin, $noSenha, $stLembreme)
	{
		$auth = new AuthenticationService();
		$sessionStorage = new SessionStorage("Geccal");
		$auth->setStorage($sessionStorage);
		$authAdapter = $this->getServiceLocator()->get('Application\Auth\Adapter');
		$authAdapter->setNoLogin($noLogin);
		$authAdapter->setNoSenha($noSenha);
		$result = $auth->authenticate($authAdapter);
		$usuario = $auth->getIdentity('user');
		$usuario = $usuario['user'];
		if($result->isValid()){
			$sessionStorage->write($auth->getIdentity('user'), null);
			$service = $this->getServiceLocator()->get("Application\Service\UsuarioService");
			$date = new \DateTime('now');
			$service->update($usuario->idUsuario,array('dtUltVisita'=>$date));
			if($stLembreme)
			{
				$this->setCookie($usuario);
			}
			return $this->redirect()->toRoute("admin-perfil",array(
					'module'=> 'admin',
					'submodule'=>'perfil',
					'action'=>'cadastrar'));
		}else{
			$this->error = true;
		}
	}
}
